package top.ninwoo.utils.util.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import top.ninwoo.utils.util.LinuxCtlUtils;
import top.ninwoo.utils.util.OvsDockerUtils;
import top.ninwoo.utils.util.Utils;

/**
 * @Author joliu
 * @Description
 * @Date　Create in 下午9:29 2019/10/20
 */
@Utils
public class OvsDockerUtilsImpl implements OvsDockerUtils {
    private static Logger LOG = LoggerFactory.getLogger(OvsDockerUtilsImpl.class);

    @Value("${cnf.passwd}")
    private String passwd;

    @Autowired
    LinuxCtlUtils linuxCtlUtils;

    @Override
    public String addPort(String bridgeName, String devName,
                          String containerId, String ip) {
        String cmd = "echo '" + passwd + "' | sudo -S ovs-docker add-port " + bridgeName
                + " " + devName + " " + containerId + " --ipaddress=" + ip;
        String res = linuxCtlUtils.runCmd(cmd);
        if(res.contains("Error")) {
            LOG.error("创建网络失败", cmd, res);
            throw new RuntimeException(cmd + ":" + res);
        }
        // 这里需要给容器设置mtu
        String mtuCmd = "docker exec " + containerId + " ifconfig eth1 mtu 1450";
        String mtuRes = linuxCtlUtils.runCmd(mtuCmd);
        //System.out.println(mtuRes);
        return res;
    }

    @Override
    public String delPort(String bridgeName, String devName, String containerId) {
        String cmd = "echo '" + passwd + "' | sudo -S ovs-docker del-port " + bridgeName + " "
                + devName + " " + containerId;

        return linuxCtlUtils.runCmd(cmd);
    }
}
